#include "UdpServer.h"

int udp_sockfd = -1;

void *udp_broadcast_listener() 
{
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_len = sizeof(client_addr);
    char buffer[1024];
    
    // 创建UDP socket
    if ((udp_sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("UDP socket creation failed");
        return NULL;
    }
    
    // 设置SO_REUSEADDR选项
    int optval = 1;
    if (setsockopt(udp_sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0) {
        perror("setsockopt SO_REUSEADDR failed");
        close(udp_sockfd);
        return NULL;
    }
    
    // 绑定到所有接口的UDP_PORT端口
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(UDP_PORT);
    
    if (bind(udp_sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("UDP bind failed");
        close(udp_sockfd);
        return NULL;
    }
    
    printf("UDP broadcast listener started on port %d\n", UDP_PORT);
    
    while (1) {
        ssize_t n = recvfrom(udp_sockfd, buffer, sizeof(buffer), 0,
                            (struct sockaddr *)&client_addr, &client_len);
        if (n < 0) {
            perror("recvfrom failed");
            continue;
        }
        
        buffer[n] = '\0';
        printf("Received UDP broadcast from %s:%d: %s\n",
               inet_ntoa(client_addr.sin_addr),
               ntohs(client_addr.sin_port),
               buffer);
        
        // 检查是否是QT客户端的发现请求
        if (strcmp(buffer, "DEVICE_DISCOVERY") == 0) {
            // 发送响应，包含TCP服务器IP和端口
            char response[256];
            snprintf(response, sizeof(response), "DEVICE_RESPONSE:%s:%d", IP, PORT);
            
            if (sendto(udp_sockfd, response, strlen(response), 0,
                      (struct sockaddr *)&client_addr, client_len) < 0) {
                perror("sendto failed");
            } else {
                printf("Sent discovery response to %s:%d\n",
                       inet_ntoa(client_addr.sin_addr),
                       ntohs(client_addr.sin_port));
            }
        }
    }
    
    close(udp_sockfd);
    return NULL;
}



void startUdpServer() 
{
    pthread_t udp_thread;
    if (pthread_create(&udp_thread, NULL, udp_broadcast_listener, NULL)) {
        ERROR("pthread_create for UDP");
        exit(-1);
    }
    pthread_detach(udp_thread);
}